package com.surelution.projects.crm

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat

import javax.imageio.ImageIO;
import javax.imageio.ImageReader
import javax.imageio.stream.ImageInputStream

class PictureService {

    static transactional = true
	
	def grailsApplication

    def storePicture(InputStream stream) {
		def picture = new Picture()
		picture.uploadTime = new Date()

		def baseDir = grailsApplication.config.binaryFile.picture.baseDir
		def sdf = new SimpleDateFormat("yyyy/MM/dd/")
		def guid = UUID.randomUUID().toString()
		picture.path = sdf.format(picture.uploadTime)
		picture.fileName = guid
		
		String path = baseDir + picture.path

		File dir = new File(path)
		if(!dir.exists()) {
			dir.mkdirs()
		}
		
		File file = new File(dir, picture.fileName)
		
		FileOutputStream fos = new FileOutputStream(file)
		fos << stream
		fos.close()
		
		stream.close()
		
		picture.fileSize = file.length()
		
		//Yes, it shits, but how...
		//get image type, eg jpeg, png etc.
		String imageType = "JPEG"
		ImageInputStream iis = ImageIO.createImageInputStream(file);
		Iterator<ImageReader> readers = ImageIO.getImageReaders(iis)
		while(readers.hasNext()) {
			ImageReader read = readers.next()
			imageType = read.getFormatName()
		}
		picture.type = imageType
		
		//get image size
		BufferedImage bi = ImageIO.read(file)
		int height = bi.height
		int width = bi.width
		picture.height = height
		picture.width = width

		return picture
    }

	def loadPicture(Picture picture) {
		def baseDir = grailsApplication.config.binaryFile.picture.baseDir
		def path = baseDir + picture.path
		return path + picture.fileName
	}
	
	def deletePicture(Picture picture) {
		def filePath = loadPicture(picture)
		def file = new File(filePath)
		file.delete()

		if(picture.exists())
			picture.delete()
		return true
	}
}
